import { loginAPI, getUserInfoAPI } from '@/api'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN(state, token) {
    setToken(token)
    state.token = token
  },
  SAVE_USERINFO(state, data) {
    state.userInfo = data
  },
  REMOVE_TOKEN(state) {
    state.token = null
    removeToken()
  },
  REMOVE_USERINFO(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login({ commit }, formData) {
    //! 登录--调登录接口，把token保存到store和cookie各一份，然后保存当前时间戳
    const token = await loginAPI(formData)
    commit('SET_TOKEN', token)
    setTimeStamp()
  },
  async getUserInfo({ commit }) {
    const data = getUserInfoAPI()
    commit('SAVE_USERINFO', data)
  },
  logout({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USERINFO')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
